package com.example.servlet;

import com.example.util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;

@WebServlet(name = "UserProfileServlet", urlPatterns = "/user-profile")
public class UserProfileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(false);
        Boolean isAdmin = session != null ? (Boolean) session.getAttribute("is_admin") : false;
        Integer userId = session != null ? (Integer) session.getAttribute("user_id") : null;
        if (isAdmin != null && isAdmin) {
            // 管理员：查询所有用户
            try (Connection conn = DBUtil.getConnection();
                 Statement stmt = conn.createStatement();
                 ResultSet rs = stmt.executeQuery("SELECT id, username, status FROM users WHERE is_admin=FALSE")) {
                StringBuilder sb = new StringBuilder();
                while (rs.next()) {
                    int id = rs.getInt("id");
                    String username = rs.getString("username");
                    String status = rs.getString("status");
                    sb.append("<tr>")
                      .append("<td>").append(id).append("</td>")
                      .append("<td>").append(username).append("</td>")
                      .append("<td>").append(status == null ? "待审核" : status).append("</td>")
                      .append("<td>")
                      .append("<form method='post' style='display:inline'>")
                      .append("<input type='hidden' name='audit_id' value='").append(id).append("'>")
                      .append("<button name='audit_action' value='pass' class='bg-green-500 text-white px-2 py-1 rounded mr-2'>通过</button>")
                      .append("<button name='audit_action' value='reject' class='bg-red-500 text-white px-2 py-1 rounded'>拒绝</button>")
                      .append("</form>")
                      .append("</td></tr>");
                }
                req.setAttribute("userTable", sb.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (userId != null) {
            // 普通用户：查询个人信息
            try (Connection conn = DBUtil.getConnection();
                 PreparedStatement ps = conn.prepareStatement("SELECT username, password, phone, address, status FROM users WHERE id=?")) {
                ps.setInt(1, userId);
                try (ResultSet rs = ps.executeQuery()) {
                    if (rs.next()) {
                        req.setAttribute("username", rs.getString("username"));
                        req.setAttribute("password", rs.getString("password"));
                        req.setAttribute("phone", rs.getString("phone"));
                        req.setAttribute("address", rs.getString("address"));
                        req.setAttribute("status", rs.getString("status") == null ? "待审核" : rs.getString("status"));
                    }
                }
                // 查询我的投稿
                List<HashMap<String, Object>> myArticles = new ArrayList<>();
                try (PreparedStatement art = conn.prepareStatement("SELECT id, title, type, create_time FROM articles WHERE author = (SELECT username FROM users WHERE id=?) ORDER BY create_time DESC")) {
                    art.setInt(1, userId);
                    try (ResultSet rs2 = art.executeQuery()) {
                        while (rs2.next()) {
                            HashMap<String, Object> map = new HashMap<>();
                            map.put("id", rs2.getInt("id"));
                            map.put("title", rs2.getString("title"));
                            map.put("type", rs2.getString("type"));
                            map.put("createTime", rs2.getTimestamp("create_time"));
                            myArticles.add(map);
                        }
                    }
                }
                req.setAttribute("myArticles", myArticles);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        req.getRequestDispatcher("user-profile.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(false);
        Boolean isAdmin = session != null ? (Boolean) session.getAttribute("is_admin") : false;
        Integer userId = session != null ? (Integer) session.getAttribute("user_id") : null;
        if (isAdmin != null && isAdmin && req.getParameter("audit_id") != null) {
            // 管理员审核
            int auditId = Integer.parseInt(req.getParameter("audit_id"));
            String action = req.getParameter("audit_action");
            String status = "pass".equals(action) ? "已通过" : "已拒绝";
            try (Connection conn = DBUtil.getConnection();
                 PreparedStatement ps = conn.prepareStatement("UPDATE users SET status=? WHERE id=?")) {
                ps.setString(1, status);
                ps.setInt(2, auditId);
                ps.executeUpdate();
            } catch (Exception e) {
                e.printStackTrace();
            }
            resp.sendRedirect("user-profile");
            return;
        } else if (userId != null) {
            // 普通用户修改个人信息
            String password = req.getParameter("password");
            try (Connection conn = DBUtil.getConnection();
                 PreparedStatement ps = conn.prepareStatement("UPDATE users SET password=? WHERE id=?")) {
                ps.setString(1, password);
                ps.setInt(2, userId);
                ps.executeUpdate();
            } catch (Exception e) {
                e.printStackTrace();
            }
            resp.sendRedirect("user-profile");
            return;
        }
        resp.sendRedirect("login.jsp");
    }
} 